extends Node2D

onready var bg = get_node("bg")
onready var joystick = get_node("joystick")
var scale = 1.0 setget set_scale

var _box_pos
var _button_pos
var _box_radius = 100
var _button_raidus = 30
var _draging = false
var _pressed_keys = []
var _button_range = []



signal on_joystick_pressed

const UP = 1
const DOWN = 2
const LEFT = 4
const RIGHT = 8

const BUTTON_VALUES = [UP|LEFT,LEFT,LEFT|DOWN,DOWN,RIGHT|DOWN,RIGHT,RIGHT|UP,UP]
const BUTTON_NAMES = {
	"5":"左上",
	"4":"左",
	"6":"左下",
	"2":"下",
	"10":"右下",
	"8":"右",
	"9":"右上",
	"1":"上",
}

func _ready():
	self.scale = 0.4
	
	_box_pos = Vector2(_box_radius+20,get_viewport_rect().size.y-_box_radius-20)
	_button_pos = _box_pos
	bg.set_pos(_box_pos)
	joystick.set_pos(_button_pos)
	set_process_input(true)
		
	var sep = PI/4
	var nv = -PI+sep
	for i in range(8):
		_button_range.push_back(nv)
		nv+=sep

func set_scale(value):
	scale = value
	bg.set_scale(Vector2(scale,scale))
	joystick.set_scale(Vector2(scale,scale))
	
func _draw():
	joystick.set_pos(_button_pos)
#	draw_circle(_box_pos,_box_radius,Color(1,1,1,0.4))
#	draw_circle(_box_pos,40,Color(0,0,0,0.5))
#	draw_circle(_button_pos,_button_raidus,Color(0,1,0,0.8))
	
func _input(event):
	var p = event.pos
	if event.type == InputEvent.MOUSE_BUTTON || event.type == InputEvent.SCREEN_TOUCH:
		if event.pressed && !_draging && pow(p.x-_box_pos.x,2)+pow(p.y-_box_pos.y,2) < pow(_box_radius,2):
			_draging = true
			
			_pressed_keys.clear()
			_button_pos = p
			update()
		elif _draging:
			_draging = false
			_button_pos = _box_pos
			for i in _pressed_keys:
				print(BUTTON_NAMES[str(i)])
			_pressed_keys.clear()
			update()
			
	elif _draging && (event.type == InputEvent.MOUSE_MOTION || event.type == InputEvent.SCREEN_DRAG):
		
		var distance_x2 = pow(p.x-_box_pos.x,2)+pow(p.y-_box_pos.y,2)
		if distance_x2 >= pow(_button_raidus,2):
			if distance_x2 < pow(_box_radius - _button_raidus,2):
				_button_pos = p
			else:
				_button_pos.x = _box_pos.x + (_box_radius-_button_raidus)*cos(atan2(p.y-_box_pos.y,p.x-_box_pos.x))
				_button_pos.y = _box_pos.y + (_box_radius-_button_raidus)*sin(atan2(p.y-_box_pos.y,p.x-_box_pos.x))
			_join_dir_with_pos(p)
	
		else:
			_button_pos = p
		update()

func _join_dir_with_pos(p):
	var n = _get_dir_from_pos(p)
	if _pressed_keys.empty():
		_pressed_keys.push_back(n)
		emit_signal("on_joystick_pressed",n)
	elif _pressed_keys.back() != n:
		_pressed_keys.push_back(n)
		emit_signal("on_joystick_pressed",n)

func _get_dir_from_pos(p):
	var cc = (p - _box_pos).angle()
	var sep = PI/8
	var i = 0
	for c in _button_range:
		if c-sep<cc && cc <= c+sep:
			return BUTTON_VALUES[i]
		i += 1
	return BUTTON_VALUES.back()
	